package com.chatplus.application.aiprocessor.listener;

import com.chatplus.application.aiprocessor.util.ChatAiUtilHandler;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.socket.WebSocketSession;

import java.util.Objects;

/**
 * 流监听器公共接口
 */
public abstract class StreamEventSourceListener extends EventSourceListener {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(StreamEventSourceListener.class);

    protected final ChatAiUtilHandler chatAiUtilHandler;
    protected StreamEventSourceListener(WebSocketSession session,
                                        AiPlatformEnum platform,
                                        String prompt) {
        chatAiUtilHandler = new ChatAiUtilHandler(session, platform, prompt);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        LOGGER.message("连接成功").context("eventSource", eventSource.request()).context("response", response).info();
        //chatAiUtilHandler.sendMessage(MessageTypeEnum.WS_START.getValue());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) {
        chatAiUtilHandler.replyErrorMessage("模型不存在或者已禁用", true);
    }

    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        super.onClosed(eventSource);
        LOGGER.message("关闭连接").info();
    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, Throwable t, Response response) {
        if (Objects.isNull(response)) {
            return;
        }
        LOGGER.message("连接异常").context("response", response).exception(t).error();
        chatAiUtilHandler.replyErrorMessage("服务端发生异常，等待管理员修复!", true);
        super.onClosed(eventSource);
        eventSource.cancel();
    }

}
